package org.rency.mq.activemq.jms.service.impl;

import org.rency.mq.activemq.constant.DestinationType;
import org.rency.mq.activemq.exception.MQException;
import org.rency.mq.activemq.jms.service.JmsAccessor;
import org.rency.mq.activemq.request.MQRequest;
import org.rency.mq.activemq.service.MQService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.jms.JMSException;
import javax.jms.Session;

/**
 * 
 * @author Administrator
 */
public class JmsService implements MQService {

	private static Logger logger = LoggerFactory.getLogger(JmsService.class);
	private JmsAccessor mqAccessor;

	public void sendMessage(MQRequest request) throws MQException {
		logger.info("Executing to send message: " + request);

		if(request.getDestination() != null){
			int destinationType = request.getDestinationType();
			
			if(destinationType != DestinationType.QUEUE && destinationType != DestinationType.TOPIC){
				throw new IllegalArgumentException("Invalid destination type:" + destinationType);
			} else {
				try {
					mqAccessor.sendMessage(request.getDestination(), destinationType, request);
				} catch (JMSException e) {
					throw new MQException(e);
				}
			}
		}else{		
			int actionId = request.getActionId();
			if (actionId >= 0) {
				mqAccessor.sendMessage(request);
			}else{
				throw new IllegalArgumentException("ActionId and destination cannot be null at same time.");
			}
		}

	}

	public Object receiveMessage(String queueName) throws MQException {
		return mqAccessor.receiveMessage(queueName);
	}

	public Object receiveMessage(int actionId) throws MQException {
		return receiveMessage(actionId, null);
	}

	public Object receiveMessage(int actionId, String selector) throws MQException {
		return receiveMessage(actionId, false, Session.AUTO_ACKNOWLEDGE, null);
	}

	public Object receiveMessage(int actionId, boolean transacted, int acknowledgeMode, String selector) throws MQException {
		logger.debug("Executing to receive message: " + actionId);
		
		if (actionId <= 0) {
			throw new IllegalArgumentException("Action id must be greater than zero.");
		}

		return mqAccessor.receiveMessage(actionId, transacted, acknowledgeMode,selector);
	}

	public void setMqAccessor(JmsAccessor mqAccessor) {
		this.mqAccessor = mqAccessor;
	}
}
